package com.iseastar.guojiang.dialog;

import java.util.ArrayList;

import android.app.Activity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.shouhuobao.station.R;
import com.iseastar.guojiang.model.ExpressCompanyBean;

import droid.frame.ui.dialog.AppDialog;

/**
 * 单选按钮列表
 * 
 * @author coffee<br>
 *         2015-9-29上午11:21:27
 */
public class AppRadioDialog<T> extends AppDialog {

	private LinearLayout mContentLayout;

	private T selectedItem;

	public AppRadioDialog(Activity context) {
		super(context);
		setContentView(R.layout.app_dialog_with_radio);
		mContentLayout = (LinearLayout) findViewById(R.id.app_dialog_content_layout);
	}

	public void setAdapter(ArrayList<T> mItems) {
		// this.mItems = mItems;
		mContentLayout.removeAllViews();
		if (mItems == null) {
			return;
		}
		for (T item : mItems) {
			View child = View.inflate(getContext(), R.layout.app_dialog_radio_item, null);
			TextView itemView = (TextView) child.findViewById(R.id.app_text);
			RadioButton radioButton = (RadioButton) child.findViewById(R.id.app_radio_button);
			if (item instanceof ExpressCompanyBean) {
				ExpressCompanyBean expressCompany = (ExpressCompanyBean) item;
				radioButton.setChecked(expressCompany.isSelected());
			} else {
				radioButton.setChecked(false);
			}
			//
			radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if (isChecked) {
						resetRedioButtonState(buttonView);
					}
				}
			});
			child.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					RadioButton radio = (RadioButton) v.findViewById(R.id.app_radio_button);
					if (radio.isSelected() == false) {
						radio.setChecked(true);
					}
				}
			});
			child.setTag(item);
			radioButton.setTag(item);
			itemView.setText(item.toString());
			mContentLayout.addView(child);
		}
	}

	public void setOnItemClickListener(View.OnClickListener onClickListener) {
		for (int i = 0; i < mContentLayout.getChildCount(); i++) {
			mContentLayout.getChildAt(i).setOnClickListener(onClickListener);
		}
	}

	@SuppressWarnings("unchecked")
	private void resetRedioButtonState(CompoundButton buttonView) {
		for (int i = 0; i < mContentLayout.getChildCount(); i++) {
			LinearLayout child = (LinearLayout) mContentLayout.getChildAt(i);
			RadioButton radio = (RadioButton) child.getChildAt(1);
			if (radio == buttonView) {
				selectedItem = (T) buttonView.getTag();
				continue;
			} else {
				radio.setChecked(false);
			}
		}
	}

	public T getSelectedItem() {
		return this.selectedItem;
	}
}
